package middleware

import (
	"benkendSystem/database"
	"benkendSystem/define"
	"benkendSystem/models"
	"github.com/gin-gonic/gin"
)

// CheckMenu  检查添加部门的菜单权限
func CheckMenu(menuName string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取上下文中的clains
		claims, _ := c.Get("claims")
		userClains := claims.(*define.UserClaims)
		menuIds := userClains.MenuIds
		var menuId int64
		if userClains.IsAdmin {
			c.Next()
			return
		}
		// 非管理员进行权限校验
		menuSet := make(map[int64]struct{})
		for _, id := range menuIds {
			menuSet[id] = struct{}{}
		}
		err := database.DB.Model(new(models.Menu)).Select("id").Joins("join role_menu rm on rm.menu_id=menu.id").Where("menu.name = ?", menuName).Find(&menuId).Error
		if err != nil {
			c.AbortWithStatusJSON(500, gin.H{
				"code": 500,
				"msg":  "系统错误",
			})
			return
		}
		if _, exists := menuSet[menuId]; !exists {
			c.AbortWithStatusJSON(403, gin.H{
				"code": 403,
				"msg":  "权限不足",
			})
			return
		}
		c.Next()

	}
}
